package com.lej.core.widget.customview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import com.lej.core.dsl.dp
import com.lej.core.utils.extention.dpf
import com.lej.core.utils.extention.safe

class TimeView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    var paint = Paint()
    var bgPaint = Paint()
    var fontMetrics: Paint.FontMetrics
    private val fontHeight: Int
    private val textWidth: Int
    val rectWidth = 19.dp
    val rectHeight = 25.dpf

    var text: String? = "123112"
        set(value) {
            field = if (value.isNullOrEmpty()) {
                "000000"
            } else
                value.replace(":", "")
            invalidate()
        }

    init {
        paint.color = Color.WHITE
        paint.textSize = 13.dpf
        fontMetrics = paint.fontMetrics
        Rect().apply { paint.getTextBounds("1", 0, 1, this) }.apply {
            fontHeight = height()
            textWidth = width()
        }
        bgPaint.color = Color.parseColor("#B1CDE9")
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        var startX = 0f

        val pointWidth = 3.dpf
        text?.forEachIndexed { i, _ ->
            canvas.drawRoundRect(startX, 0f, rectWidth + startX, 25.dpf, 3.dpf, 3.dpf, bgPaint)
            val drawY = rectHeight - (rectHeight - fontHeight) / 2
            canvas.drawText(text!!, i, i + 1, startX + (rectWidth - textWidth) / 2, drawY, paint)
            if (i % 2 == 1 && i != text!!.length - 1) {
                val rectX = 5.dp + startX + rectWidth
                canvas.drawRect(rectX, 12.dpf, rectX + pointWidth, 12.dpf + pointWidth, bgPaint)
                canvas.drawRect(rectX, 17.dpf, rectX + pointWidth, 17.dpf + pointWidth, bgPaint)
                startX += (rectWidth + 13.dp)
            } else {
                startX += (rectWidth + 3.dp)
            }
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val length = text?.length.safe()
        val measureWidth = rectWidth * length + 3.dp * (length / 2) + 13.dp * ((length + 1) / 2 - 1)
        val widthSpec = MeasureSpec.makeMeasureSpec(measureWidth, MeasureSpec.getMode(widthMeasureSpec))
        val heightSpec = MeasureSpec.makeMeasureSpec(25.dp, MeasureSpec.getMode(widthMeasureSpec))
        setMeasuredDimension(getDefaultSize(measureWidth, widthSpec), getDefaultSize(measureWidth, heightSpec))
    }
}